package cn.ciis.basic.event;

import cn.ciis.basic.base.BaseCache;
import com.jfinal.kit.LogKit;
import com.jfinal.kit.Ret;
import net.dreamlu.event.core.EventListener;
import org.tio.core.Tio;

public class CheckIpEventListen {

    /**
     * 判断是否需要将IP地址拉黑
     * @param event
     */
    @EventListener(async = true)
    public void listenCheckIpEvent(CheckIpEvent event){

        Ret ret = BaseCache.IPBLACK.get(event.getChannelContext().getClientNode().getIp());//获取当前Ip上次上传错误数据的时间
        if(ret == null){
            ret=Ret.create().set("count", 1).set("errorTime", System.currentTimeMillis());
            BaseCache.IPBLACK.put(event.getChannelContext().getClientNode().getIp(),ret);
        }else{
            long result = System.currentTimeMillis() - ret.getLong("errorTime");
            if(result <1800000){//半个小时之内
                if(ret.getInt("count") == 2){
                    Tio.IpBlacklist.add(event.getChannelContext().tioConfig, event.getChannelContext().getClientNode().getIp());
                    LogKit.error("已将IP地址{}加入黑名单",event.getChannelContext().getClientNode().getIp());
                }else{
                    ret.set("count", ret.getInt("count") + 1);
                }
            }else{
                ret.set("count",1).set("errorTime", System.currentTimeMillis());
                BaseCache.IPBLACK.put(event.getChannelContext().getClientNode().getIp(),ret);
            }

        }
    }

}
